package com.seven.dao;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seven.domain.Ticket;
import com.seven.mapper.TicketMapper;
import com.seven.util.HeaderUtil;
import java.math.BigDecimal;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class TicketDao {

    @Autowired
    private TicketMapper ticketMapper;

    public void insert(Ticket ticket) {
        ticketMapper.insert(ticket);
    }

    public List<Ticket> selectList(String userName, String groupName, String number) {
        QueryWrapper<Ticket> queryWrapper = new QueryWrapper<Ticket>().eq("user_name", userName).eq("group_name", groupName).eq("number", number);
        return ticketMapper.selectList(queryWrapper);
    }

    public IPage<Ticket> selectPage(Page<Ticket> pageParam, String userName) {
        QueryWrapper<Ticket> selectParam = new QueryWrapper<Ticket>().eq("deleted", 0);
        if (Strings.isNotBlank(userName)) {
            selectParam.eq("user_name", userName);
        }
        String token = HeaderUtil.getToken();
        if (token != null) {
            selectParam.eq("token", token);
        }
        return ticketMapper.selectPage(pageParam, selectParam);
    }

    public Ticket selectById(String id) {
        Ticket ticket = ticketMapper.selectById(id);
        if (ticket != null && ticket.getDeleted()) {
            log.info("ticket not exist. id {}", id);
            ticket = null;
        }
        return ticket;
    }

    public List<Ticket> selectBatchIds(List<String> idList) {
        List<Ticket> tickets = ticketMapper.selectBatchIds(idList);
        return tickets.stream().filter(ticket -> !ticket.getDeleted()).sorted().collect(Collectors.toList());
    }

    public void softDeleteById(String id) {
        Ticket ticket = new Ticket();
        ticket.setId(id);
        ticket.setDeleted(true);
        ticketMapper.updateById(ticket);
    }
}
